package home.projects.misc.classloader;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

public class ClassLoaderTest {

    public static void main(final String[] args) throws Throwable {
        File f = new File("E:\\rnd\\eclipse-workspace\\Services\\WebContent\\WEB-INF\\lib\\commons-lang-2.4.jar");
        URL url = f.toURL();
        CustomUrlClassLoader uclOne = new CustomUrlClassLoader(new URL[] { url },
                ClassLoaderTest.class.getClassLoader(), "FIRST");
        CustomUrlClassLoader uclTwo = new CustomUrlClassLoader(new URL[] { url }, uclOne, "SECOND");
        Class<?> klass = uclTwo.loadClass("org.apache.commons.lang.enum.ValuedEnum");
        System.out.println(klass);
    }
}

class CustomUrlClassLoader extends URLClassLoader {

    private String name;
    
    public CustomUrlClassLoader(URL[] urls, ClassLoader parent, String name) {
        super(urls, parent);
        this.name = name;
    }

    public CustomUrlClassLoader(URL[] urls, String name) {
        this(urls, null, name);
    }
   
    @Override
    public String toString() {
        return "Classloader-" + this.name;
    }
//    @Override
//    protected Class<?> findClass(final String className)throws ClassNotFoundException {
//        Class<?> klass;
//        try {
//            klass = super.findClass(className);
//            System.out.println("Loaded class " + className + " using loader " + this.name + ".");
//        } catch(ClassNotFoundException e) {
//            System.out.println("Failure to load class " + className + " using loader " + this.name + ".");
//            throw e;
//        }
//        return klass;
//    }

    @Override
    protected synchronized Class<?> loadClass(String className, boolean resolve)
            throws ClassNotFoundException {
        Class<?> klass;
        try {
            klass = findClass(className);
            if(klass == null) {
                klass = super.loadClass(className, resolve);
            }
            System.out.println("Loaded class " + className + " using loader " + klass.getClassLoader() + ".");
        } catch(ClassNotFoundException e) {
            System.out.println("Failure to load class " + className + " using loader " + this.name + ".");
            throw e;
        }
        return klass;
    }
    
    
    
}
